package cn.janescott.file.server.servlet;

import cn.janescott.file.server.FileServerStarter;
import cn.janescott.file.server.dao.FileDao;
import cn.janescott.file.server.dto.FileInfoDTO;
import cn.janescott.file.server.dto.ResultDTO;
import cn.janescott.file.server.processor.BinaryProcessor;
import org.eclipse.jetty.http.MimeTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;

/**
 * 图片服务器
 *
 * @author scott
 * @date 2019/4/12
 */
public class FileServlet extends HttpServlet {
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 文件
     */
    private static final String MULTIPART_FORM = MimeTypes.Type.MULTIPART_FORM_DATA.asString();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("get");
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("post");
        BinaryProcessor processor = getProcessor();
        FileDao dao = getDao();
        ResultDTO result = new ResultDTO();
        try {
            Collection<Part> parts = req.getParts();
            if (parts != null && parts.size() > 0) {
                ResultDTO.Data data = new ResultDTO.Data();
                for (Part part : parts) {
                    FileInfoDTO fileInfo = processor.upload(part);
                    dao.save(fileInfo);
                    data.getSuccMap().put(fileInfo.getName(), fileInfo.getPath());
                }
                result.setCode("1");
                result.setData(data);
            } else {
                resp.sendError(400, "文件不能为空");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.sendError(500, "上传失败");
        }
    }

    /**
     * 获取数据库服务
     *
     * @return
     */
    private FileDao getDao() {
        return (FileDao) FileServerStarter.get(FileDao.class);
    }

    /**
     * 获取文件服务
     *
     * @return
     */
    private BinaryProcessor getProcessor() {
        return (BinaryProcessor) FileServerStarter.get(BinaryProcessor.class);
    }
}
